﻿using System;
using System.Diagnostics.Contracts;
using System.Reflection;
using Diagnostics = Commons.Diagnostics;

namespace Commons.Extension
{
    internal static class EventExtension
    {
        internal static void RaiseEventFromSap<T>( this object aInvoker, string aEventName, T aEventArguments )
        {
            Diagnostics.Contract.Requires.NotNull( () => aInvoker );

            FieldInfo lEventField = aInvoker.GetType().GetField( aEventName, BindingFlags.Instance | BindingFlags.NonPublic );

            Diagnostics.Contract.Assert.NotNull( () => lEventField );

            MulticastDelegate lEventDelegateMethods = (MulticastDelegate)lEventField.GetValue( aInvoker );

            if ( lEventDelegateMethods == null )
            {
                return;
            }

            foreach ( Delegate lEventDelegateHandler in lEventDelegateMethods.GetInvocationList() )
            {
                lEventDelegateHandler.Method.Invoke( lEventDelegateHandler.Target, new object[] { aEventArguments } );
            }
        }
    }
}